package com.yang.controller;


import com.yang.domain.Result;
import com.yang.domain.VO.MenuTreeVo;
import com.yang.domain.VO.MenuVo;
import com.yang.domain.VO.RoleMenuTreeSelectVo;
import com.yang.domain.entity.Menu;
import com.yang.service.MenuService;
import com.yang.utils.BeanCopyUtils;
import com.yang.utils.SystemConverter;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


/**
 * <p>
 * 后台菜单控制层
 * </p>
 * @author yang
 * @date 2023/5/29
 */
@RestController
@RequestMapping("/system/menu")
public class MenuController {

    @Resource
    private MenuService menuService;
    /**
     * 获取菜单列表
     */
    @GetMapping("/list")
    public Result list(Menu menu) {
        List<Menu> menus = menuService.selectMenuList(menu);
        List<MenuVo> menuVos = BeanCopyUtils.copyBeanList(menus, MenuVo.class);
        return Result.okResult(menuVos);
    }

    @PostMapping
    public Result add(@RequestBody Menu menu) {
        menuService.save(menu);
        return Result.okResult();
    }

    /**
     * 修改菜单
     */
    @PutMapping
    public Result edit(@RequestBody Menu menu) {
        if (menu.getId().equals(menu.getParentId())) {
            return Result.errorResult(500,"修改菜单'" + menu.getMenuName() + "失败，上级菜单不能选择自己");
        }
        menuService.updateById(menu);
        return Result.okResult();
    }

    /**
     * 删除菜单
     */
    @DeleteMapping("/{menuId}")
    public Result remove(@PathVariable("menuId") Long menuId) {
        if (menuService.hasChild(menuId)) {
            return Result.errorResult(500,"存在子菜单不允许删除");
        }
        menuService.removeById(menuId);
        return Result.okResult();
    }


    /**
     * 根据菜单编号获取详细信息
     */
    @GetMapping(value = "/{menuId}")
    public Result getInfo(@PathVariable Long menuId) {

        return Result.okResult(menuService.getById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public Result treeSelect() {
        //复用之前的selectMenuList方法。方法需要参数，参数可以用来进行条件查询，而这个方法不需要条件，所以直接new Menu()传入
        List<Menu> menus = menuService.selectMenuList(new Menu());

        List<MenuTreeVo> options =  SystemConverter.buildMenuSelectTree(menus);

        return Result.okResult(options);
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public Result roleMenuTreeSelect(@PathVariable("roleId") Long roleId) {
        //1.查询出所有菜单
        List<Menu> menus = menuService.selectMenuList(new Menu());
        //2.根据角色当前角色的权限路由
        List<Long> checkedKeys = menuService.selectMenuListByRoleId(roleId);
        //3.构建树
        List<MenuTreeVo> menuTreeVos = SystemConverter.buildMenuSelectTree(menus);

        RoleMenuTreeSelectVo vo = new RoleMenuTreeSelectVo(checkedKeys,menuTreeVos);

        return Result.okResult(vo);
    }
}
